package com.sky.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;

@Configuration
public class ThreadPoolConfiguration {

    @Bean
    public ThreadPoolExecutor threadPool(){
        // 准备创建线程池所需要的7个参数
        int corePoolSize = 4;
        int maximumPoolSize = 8;
        int keepLiveTime = 10;
        TimeUnit timeUnit = TimeUnit.SECONDS;
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        ArrayBlockingQueue queue = new ArrayBlockingQueue<>(3);

        RejectedExecutionHandler policy =
                // 当触发拒绝策略所满足条件时会抛出异常：java.util.concurrent.RejectedExecutionException
                // new ThreadPoolExecutor.AbortPolicy();
                // 当触发拒绝策略所满足条件时会将任务转回调用者（main线程）执行
                // new ThreadPoolExecutor.CallerRunsPolicy();
                // 当触发拒绝策略所满足条件时会放弃等待时间最长的那个任务
                // new ThreadPoolExecutor.DiscardOldestPolicy();
                // 当触发拒绝策略所满足条件时会静默丢弃新的任务
                new ThreadPoolExecutor.DiscardOldestPolicy();

        // 创建线程池对象
        ThreadPoolExecutor myThreadPool = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepLiveTime,
                timeUnit,
                queue,
                threadFactory,
                policy);

        return myThreadPool;
    }

}